package com.haorui.lygyd.authority.filter;

import com.haorui.base.core.ConfigValue;
import com.haorui.lygyd.authority.authentication.PermsAuthenticationToken;
import com.haorui.lygyd.authority.jwt.JwtTokenUtil;
import com.haorui.lygyd.authority.service.AccountDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.www.NonceExpiredException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2017/8/10
 * 时间: 0:08
 * 功能：请进行修改
 */
@Component
@Order(1)
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    AccountDetailService accountDetailService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    ConfigValue configValue;
    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.authPath}")
    private String authPath;
//    @Value("${whiteurl}")
    private List<String> whiteUrl;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
       String url=httpServletRequest.getRequestURI();
        System.out.println(httpServletRequest.getMethod());
       if(url.contains(authPath) ||  httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())){
           filterChain.doFilter(httpServletRequest, httpServletResponse);
           return;
       }
        String authHeader = httpServletRequest.getHeader(this.tokenHeader);
        if(authHeader!=null && authHeader.startsWith(tokenHead)) {
            PermsAuthenticationToken permsAuthenticationToken = new PermsAuthenticationToken(this.tokenHead, authHeader, httpServletRequest);
            try{
                authenticationManager.authenticate(permsAuthenticationToken);
            }catch (NonceExpiredException e){
               httpServletResponse.sendError(419,e.getMessage());
               return;
            }

        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
